﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Toulr.Services;
using Toulr.Util.Ioc;
using Toulr.Models;
using Toulr.Models.Account;
using Toulr.Domains.Account;

public partial class Account_Login : CommPageBase
{
    IUserContextService service;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            service = UnityHelper.GetInstance<IUserContextService>();

            //Response.Cookies.Remove("userinfo");

            ActionResult<User> actionResult = service.Login(new LoginModel() { Email = txtEmail.Value, Password = txtPwd.Value });

            if (actionResult.ResultCode == 0)
            {
                PageHelper.CurrentUser = actionResult.Result;
                if (chbRememberMe.Checked)
                {
                    SetCookie(txtEmail.Value, txtPwd.Value);
                }

                //success
                if (!string.IsNullOrEmpty(PageHelper.ReturnUrl))
                {
                    string url = PageHelper.ReturnUrl;
                    PageHelper.ReturnUrl = null;
                    Response.Redirect(url);
                }
                else
                {
                    Response.Redirect(PageHelper.Url("default.aspx"));
                }
            }
            else
            {
                AddClientErrorMessageBox("错误提示", actionResult.Tips);
            }
        }
        else
        {
            if (Request["type"] != null && Request["type"].ToLower() == "logout")
            {
                AddClientErrorMessageBox("错误提示", "已经安全退出偷乐网！");
            }
        }
    }

    /// <summary>
    /// Sets the cookie.
    /// </summary>
    /// <param name="email">The email.</param>
    /// <param name="pwd">The PWD.</param>
    /// <Author>Tecky Lee</Author>
    /// <Date>2011/5/26 9:43</Date>
    private void SetCookie(string email, string pwd)
    {
        ActionResult<string> actionResult = service.EncodeUserInfoForCookie(email, pwd);
        if (actionResult.ResultCode != 0)
        {
            return;
        }

        HttpCookie cookie = Request.Cookies["userinfo"];
        if (cookie != null)
        {
            cookie.Value = actionResult.Result;
        }
        else
        {
            cookie = new HttpCookie("userinfo", actionResult.Result);
            //设置14天后过期
            cookie.Expires = DateTime.Now.AddDays(14);
        }
        Response.AppendCookie(cookie);
    }
}
